package com.sx.pipeline.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.sx.mvvmlibs.bus.RxBus;
import com.sx.mvvmlibs.utils.Logs;
import com.sx.pipeline.R;
import com.sx.pipeline.app.event.WxEntryRespEvent;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * @Author: YY
 * @Date: 2021/11/23
 * @Describe: TODO
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = WXEntryActivity.class.getSimpleName();

    private IWXAPI api;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, getString(R.string.wx_app_id));
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReq(BaseReq req) {
        Log.e(TAG, "onReq: " + req);
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG,"onResp: " + resp);
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    SendAuth.Resp authResp = (SendAuth.Resp) resp;
                    RxBus.getDefault().post(new WxEntryRespEvent<>(resp.getType(),
                            resp.errCode, authResp.code, null));
                    Log.d(TAG, "授权成功 ");
                    ToastUtils.showShort("授权成功");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    ToastUtils.showShort("取消授权");
                    break;
                default:
                    ToastUtils.showShort("授权失败");
                    break;
            }
        }
        finish();
    }
}
